package com.detrum.detrumdx.fragment;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.detrum.base.ServiceStatic;
import com.detrum.bean.ViewPagerItem;
import com.detrum.costomview.MyViewPager;
import com.detrum.costomview.MyViewPagerCall;
import com.detrum.detrumdx.R;
import com.detrum.detrumdx.base.DetrumApp;
import com.detrum.detrumdx.base.DeviceStatic;
import com.detrum.sqlite.SqliteDeviceOperate;
import com.detrum.utils.LogUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link DeviceFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DeviceFragment extends Fragment implements View.OnClickListener {

    private OnFragmentInteractionListener mListener;

    private Context context;
    private final int OWN_DEVICE = 0;
    private final int MORE_DEVICE = 1;
    private TextView enter_camera, tvOwnDevice, tvMoreDevice;
    private MyViewPager myViewPager, myViewpager2;
    private List<ViewPagerItem> list, list_2;
    private final int OWNList = 100;
    int imageIds[] = new int[]{R.mipmap.wurenji1,
            R.mipmap.chuanyueji, R.mipmap.wurenji, R.mipmap.yuntai};
    private static int flag;
    private int currentPosition;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == OWNList) {
                LogUtils.e("DeviceFragment size = "+list.size());
                myViewPager.setList(list);
                if(currentPosition>=list.size()){
                    currentPosition = 0;
                }
                LogUtils.e("ServiceStatic.isLaunchUsbService = "+ServiceStatic.isLaunchUsbService);
                if(ServiceStatic.isAccessoryConnect){
                    currentPosition=1;
                }else{
                    currentPosition=0;
                }
                myViewPager.setItem(currentPosition);
                if(list.get(currentPosition).getName().contains("IWT")){
                    UsbIsShow();
                }else{
                    OtherIsShow();
                }
                myViewPager.setMyViewPagerCall(new MyViewPagerCall() {
                    @Override
                    public void onClick(View view, int position) {

                    }

                    @Override
                    public void SelectItem(int position) {
                        currentPosition = position;
                        if(list.get(position).getName().contains("IWT")){
                            UsbIsShow();
                        }else if(list.get(position).getName().contains("DCAM")){
                            OtherIsShow();
                        }
                    }
                });
            }
        }
    };

    private void UsbIsShow(){
        if(!ServiceStatic.isAccessoryConnect){
            enter_camera.setVisibility(View.INVISIBLE);
        }else{
            enter_camera.setVisibility(View.VISIBLE);
        }
    }

    private void OtherIsShow(){
        if(!ServiceStatic.isAccessoryConnect){
            enter_camera.setVisibility(View.VISIBLE);
        }else{
            enter_camera.setVisibility(View.INVISIBLE);
        }
    }

    public void setList(boolean isSuccess){
        if(isSuccess){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if(list!=null){
                        list.clear();
                    }
                    list = SqliteDeviceOperate.getInstance(context).SelectAll();
                    for (int i = 0; i < list.size(); i++) {
                        if(list.get(i).getName().contains("IWT")){
                            currentPosition = i;
                        }
                    }
                    handler.sendEmptyMessage(OWNList);
                }
            }).start();

        }
    }

    public void usbDisconnect(){
        if(flag==0){
            if(list==null||list.size()==0){
                return;
            }
            currentPosition = 0;
            myViewPager.setItem(currentPosition);
            final String name = list.get(currentPosition).getName();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if(name.contains("IWT")){
                        enter_camera.setVisibility(View.INVISIBLE);
                    }else if(name.contains("DCAM")){
                        enter_camera.setVisibility(View.VISIBLE);
                    }
                }
            });

        }
    }

    public static DeviceFragment newInstance() {
        DeviceFragment fragment = new DeviceFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_device, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.e("DeviceFragment onResume");
        list_2.clear();
        for (int i = 0; i < imageIds.length; i++) {
            ViewPagerItem item = new ViewPagerItem();
            item.setName("无人机" + (i + 1));
            item.setMsg("拥有该机" + 50 * (i + 1) + "天");
            item.setImage(imageIds[i]);
            list_2.add(item);
        }
        myViewpager2.setList(list_2);
        myViewpager2.setMyViewPagerCall(new MyViewPagerCall() {
            @Override
            public void onClick(View view, int position) {
                //此处跳转无人机详情
                connectDevice(position);
            }

            @Override
            public void SelectItem(int position) {
                currentPosition = position;
            }
        });
        onClickedDeviceSwitch(flag);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    private void initView(View parentView) {
        tvOwnDevice = parentView.findViewById(R.id.tv_own_device);
        tvMoreDevice = parentView.findViewById(R.id.tv_more_device);
        myViewPager = parentView.findViewById(R.id.my_viewpager);
        list_2 = new ArrayList<>();
        enter_camera = parentView.findViewById(R.id.enter_camera);
        myViewpager2 = parentView.findViewById(R.id.my_viewpager2);
        tvOwnDevice.setOnClickListener(this);
        tvMoreDevice.setOnClickListener(this);
        enter_camera.setOnClickListener(this);
    }

    private void onClickedDeviceSwitch(int arg) {
        switch (arg) {
            case OWN_DEVICE:
                showOwn();
                myViewPager.setVisibility(View.VISIBLE);
                myViewpager2.setVisibility(View.GONE);
                //加载本地数据库--保留之前已访问过的无人机设备

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        list = SqliteDeviceOperate.getInstance(DetrumApp.appInstance()).SelectAll();
                        if(list!=null&&list.size()!=0){
                            handler.sendEmptyMessage(OWNList);
                            return;
                        }
                        ViewPagerItem item1 = new ViewPagerItem();
                        item1.setName("DCAM-H");
                        item1.setMsg("0.0.1.20180316121212");
                        item1.setImage(R.mipmap.sport);
                        SqliteDeviceOperate.getInstance(DetrumApp.appInstance()).Insert(item1);
                        ViewPagerItem item2 = new ViewPagerItem();
                        item2.setName("IWT-AGS58");
                        item2.setMsg("0.0.1.20180316121212");
                        item2.setImage(R.mipmap.mslogo);
                        SqliteDeviceOperate.getInstance(DetrumApp.appInstance()).Insert(item2);
                        list = SqliteDeviceOperate.getInstance(DetrumApp.appInstance()).SelectAll();
                        handler.sendEmptyMessage(OWNList);
                    }
                }).start();
                flag = 0;
                break;
            case MORE_DEVICE:
                showMore();
                if(currentPosition<list_2.size()){
                    myViewpager2.setItem(currentPosition);
                }
                flag = 1;
                break;
        }
    }

    private void showOwn() {
        tvOwnDevice.setTextColor(getResources().getColor(R.color.gray_4a));
        tvOwnDevice.setBackgroundResource(R.drawable.shape_tv_owndevice_bg_true);
        tvMoreDevice.setTextColor(getResources().getColor(R.color.gray_b));
        tvMoreDevice.setBackgroundResource(R.drawable.shape_tv_owndevice_bg_false);
        enter_camera.setVisibility(View.INVISIBLE);
    }

    private void showMore() {
        tvMoreDevice.setTextColor(getResources().getColor(R.color.gray_4a));
        tvMoreDevice.setBackgroundResource(R.drawable.shape_tv_owndevice_bg_true);
        tvOwnDevice.setTextColor(getResources().getColor(R.color.gray_b));
        tvOwnDevice.setBackgroundResource(R.drawable.shape_tv_owndevice_bg_false);
        myViewpager2.setVisibility(View.VISIBLE);
        enter_camera.setVisibility(View.GONE);
        myViewPager.setVisibility(View.GONE);
        myViewpager2.UpData(list_2, 0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_own_device:
                currentPosition = 0;
                onClickedDeviceSwitch(OWN_DEVICE);
                break;
            case R.id.tv_more_device:
                currentPosition = 0;
                onClickedDeviceSwitch(MORE_DEVICE);
                break;
            case R.id.enter_camera:
                if (flag == 0) {
                    if(list==null||list.size()==0){
                        return;
                    }
                    mListener.EnterDevice(list.get(myViewPager.getItem()).getName());
                    // MyMethod.toActivity(context, UAVPreviewActivity.class);
                } else if (flag == 1) {
                    int item = myViewpager2.getItem();
                    // connectDevice(item);
                }
                break;
            default:
                break;
        }
    }

    //广告
    private void connectDevice(int tag) {
        if (tag == 0) {
            mListener.StartDetails(DeviceStatic.FeiKong);
        } else if (tag == 1) {
            mListener.StartDetails(DeviceStatic.SportCamera);
        } else if (tag == 2) {
            mListener.StartDetails(DeviceStatic.Digifax);
        } else if (tag == 3) {
            // TODO: 2018/1/31 连接成功写入数据库 
            Log.e("dawegiopjag", "连接手持云台");
            mListener.StartDetails(DeviceStatic.HardDeck);
            //MyMethod.toActivity(context, CameraPreview.class);
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);

        void StartDetails(String name);

        void EnterDevice(String name);
    }
}
